package com.wchat.network.device;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.util.ArrayList;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

import com.wchat.network.Controller;
import com.wchat.network.message.Message;

@Root
public class Group implements SendTarget, Serializable {

	private static final long serialVersionUID = 2434176528339019449L;

	@Attribute
	private long groupid;

	@Element
	private GroupParam param = new GroupParam();

	@Override
	public InetAddress getAddress() {
		return null;
	}

	@Override
	public void sendMessage(Message message) throws IOException {
		DeviceContext deviceContext = Controller.getInstance().getDeviceContext();
		ArrayList<Device> devices = deviceContext.getDevicesInGroup(groupid);
		int size = devices.size();
		for (int i = 0; i < size; i++) {
			Device device = devices.get(i);
			if (device != null) {
				device.sendMessage(message);
			}
		}
	}

	public long getGroupid() {
		return groupid;
	}

	public void setGroupid(long groupid) {
		this.groupid = groupid;
	}

	public GroupParam getParam() {
		return param;
	}

	public void setParam(GroupParam param) {
		this.param = param;
	}


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (groupid ^ (groupid >>> 32));
		result = prime * result + ((param == null) ? 0 : param.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Group other = (Group) obj;
		if (groupid != other.groupid)
			return false;
		if (param == null) {
			if (other.param != null)
				return false;
		} else if (!param.equals(other.param))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Group [groupid=" + groupid + ", param=" + param + "]";
	}

}
